<template>
	<view class="base-page">
		<view class="yangsf-padding-20 yangsf-flex-col-center">
			<view class="">
				<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="6" multiple
					:maxCount="1" width="250" height="150">
					<image src="/static/img/sfz.png" mode="widthFix" style="width: 250px;height: 150px;"></image>
				</u-upload>
			</view>

			<view class="yangsf-m-t-100">
				<u--form labelPosition="left" :model="userMsg" :rules="rules" labelWidth="80" ref="uForm">
					<u-form-item label="真实姓名" prop="realname" borderBottom ref="item1">
						<u--input v-model="userMsg.realname" border="none" placeholder="上传图片自动识别"></u--input>
					</u-form-item>
					<u-form-item label="证件号" prop="idcard" borderBottom ref="item1">
						<u--input v-model="userMsg.idcard" border="none" placeholder="上传图片自动识别"></u--input>
					</u-form-item>

					<u-form-item label="手机号" prop="tele" borderBottom ref="item1">
						<u--input v-model="userMsg.tele" border="none" placeholder="手机号, 可用于登录"></u--input>
					</u-form-item>

					<view class="yangsf-m-t-60">
						<u-button type="primary" @click="submit">提交</u-button>
					</view>
				</u--form>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		baseUrl,
		domainNameUrl
	} from '@/config/config.js'
	import {
		submitAuth,
		checkTele
	} from '@/config/api.js'
	export default {
		data() {
			return {
				imgUrl: '',
				fileList: [],
				userMsg: {
					realname: '',
					sex: '',
					idcard: '',
					tele: '',
					address: ''
				},
				rules: {
					'realname': [{
						type: 'string',
						required: true,
						message: '真实姓名不能为空',
						trigger: ['blur', 'change']
					}],
					'idcard': [{
						type: 'string',
						required: true,
						message: '证件号不能为空',
						trigger: ['blur', 'change']
					}, {
						type: 'string',
						required: true,
						min: 3,
						max: 20,
						message: '证件号不符合规范',
						trigger: ['blur', 'change']
					}],
					'tele': [{
						type: 'string',
						required: true,
						message: '手机号号不能为空',
						trigger: ['blur', 'change']
					}, {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}, {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							return this.checkTele(rule, value, callback);
						},
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}]
				}
			}
		},
		methods: {
			checkTele(rule, value, callback){
				if(!value || value == ''){
					callback(new Error('手机号不能为空'));
				}
				else{
					let data = {
						tele: value
					}
					checkTele(data).then(res => {
						console.log("校验结果 ==> {}",res);
						console.log("res.data.flag == 1 ==> {}",res.data.flag == 1);
						if(res.code == 200){
							if(res.data.flag && res.data.flag == 1){
								console.log("校验通过, 需要执行一下");
								callback()
							}
							else{
								callback(new Error('系统存在当前手机号，请更换'));
							}
						}
						
					})
				}
			},
			submit() {
				this.$refs.uForm.validate().then(res => {
					uni.$u.toast('校验通过')
					let data = {
						tele: this.userMsg.tele,
						realName: this.userMsg.realname,
						idCard: this.userMsg.idcard
					}
					submitAuth(data).then(res => {
						console.log("获取人脸识别地址 ==> {}", res);
						if (res.code == 200) {
							console.log("获取人脸识别地址 ==> {}", res.data);
							uni.$u.route({
								type: 'reLaunch',
								url: '/pages/auth/face',
								params: {
									pageUrl: res.data + ''
								}
							});
						} else {
							uni.$u.toast(res.msg)
						}
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.userMsg.realname = '';
				this.userMsg.sex = '';
				this.userMsg.idcard = '';
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let obj = lists[0];
				let fileListLen = this.fileList.length;
				this.fileList.push({
					...obj,
					status: "uploading",
					message: "识别中",
				});
				const result = await this.uploadFilePromise(obj.url, fileListLen);
			},
			uploadFilePromise(url, index) {
				return new Promise((resolve, reject) => {
						uni.uploadFile({
						url: baseUrl + "/ocr/idCard",
						// url: domainNameUrl + "/ocr/idCard",
						filePath: url,
						name: "file",
						formData: {
							side: "front",
						},
						success: (res) => {
							let resData = JSON.parse(res.data);
							console.log("res ==> {}", resData);
							let userData = JSON.parse(resData.data);
							this.userMsg.realname = userData.realname;
							this.userMsg.sex = userData.sex;
							this.userMsg.idcard = userData.idcard;

							this.fileList.splice(
									index,
								1,
								Object.assign(this.fileList[index], {
									status: "success",
									message: "",
									url: url,
								})
							);
							resolve(url);
						},
						fail: (err) => {
								this.fileList.splice(
									index,
									1,
									Object.assign(this.fileList[index], {
										status: "failed",
										message: "识别失败",
									})
								);
								reject(err);
							}
					});
				});
			},
		}
	}
</script>

<style>

</style>